import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home'
import Login from '../views/Login'
import Index from "../views/Index";
import NotFound from "../views/NotFound";
import axios from "../axios"; //引入自己创建的axios，这样会按自己写的代码进行拦截
import store from "../store";

Vue.use(Router)

const router = new Router({
  mode:"history",
  routes: [
    {
      path: '/home',
      name: 'Home',
      component: Home,
      children:[
        {
          path: '/index',
          name: 'Index',
          component: Index
        },
        {
          path: '/userCenter',
          name: 'UserCenter',
          component: ()=>import('@/views/UserCenter'), //懒加载路由
          meta:{
            title:"修改密码"
          }
        }
        //{
        //   path: '/sys/user',
        //   name: 'User',
        //   component: UserManage
        // },{
        //   path: '/sys/role',
        //   name: 'Role',
        //   component: RoleManage
        // },{
        //   path: '/sys/menu',
        //   name: 'Menu',
        //   component: MenuManage
        // },
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: "*",
      component: NotFound,
    }
  ],
})

//在此进行动态路由绑定
router.beforeEach((to, from, next) => {

  let token = localStorage.getItem("token");  //本地没有任何token则跳到登录页，防止个人删除网页token不跳转
  if(to.path == "/login"){
    next();
  }else if(!token){
    next({name:Login});
  }else {
    let hasRoute = store.state.menus.hasRoute;

    if(token && !hasRoute){   //有 token没有路由则从后端获取路由
      axios.get("/sys/menu/nav",{
        headers:{
          Authorization:localStorage.getItem('token')
        }
      }).then(res=>{
        store.commit("setHasRoute",true)
        //从后端拿到用户对应的导航栏菜单
        store.commit("setMenuList",res.data.data.nav)
        //拿到用户权限
        store.commit("setPermList",res.data.data.authoritys)

        //动态添加路由
        res.data.data.nav.forEach(menu=>{
          if(menu.children){
            menu.children.forEach(e=>{
              let route = menuToRoute(e);
              if(route){
                router.addRoute('Home',route) //添加到名为Home的父路由下
              }
            })
          }
        })
      })
    }
    next();
  }
})


//菜单转化成路由
const menuToRoute=(menu)=>{
  if (!menu.component){
    return null;
  }
  let route={
    name:menu.name,
    path:menu.path,
    component:()=>import('@/views'+menu.component),
    meta:{
      icon:menu.icon,
      title:menu.title
    }
  };
  return route;
}

export default router;
